package com.chmingx.JavaBasic.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.80.130");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接
            connection = connectionFactory.newConnection("生产者");
            // 通过连接获取channel
            channel = connection.createChannel();
            // 通过创建交换机，声明队列，绑定关系，路由key，发送消息，接收消息
            String queueName = "simple";

            /*
            * 队列名字
            * 是否要持久化
            * 排他性，是否为独占
            * 是否自动删除，最后一个消息被消费后队列是否自动删除
            * 携带一些附加参数
            * */
            channel.queueDeclare(queueName, false, false, false, null);
            // 准备消息内容
            String message = "hello rabbit!";
            // 发送消息给队列
            channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel
            if (channel != null && channel.isOpen()) {

                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

